import { get } from 'lodash'
import {
    initPallette,
    colorPaletteClick,
    colorPalette,
    closeColorPalette
} from './colorPalette.js'
// 独立分栏功能区域 dom结构
const subfieldBoxDom = document.createElement('div')
subfieldBoxDom.id = 'subfield-box'
subfieldBoxDom.innerHTML = `
<div class="subfield">
    <div class="subfield-item del" title="删除">
        <img src="${require('@/assets/icons/editor/del-subfield.png')}" />
    </div>
    <div class="subfield-item set-left" title="向左插入一栏">
        <img src="${require('@/assets/icons/editor/set-left.png')}" />
    </div>
    <div class="subfield-item set-right" title="向右插入一栏">
        <img src="${require('@/assets/icons/editor/set-right.png')}" />
    </div>
    <div class="subfield-item palette" title="背景颜色">
        <img src="${require('@/assets/icons/editor/palette.png')}" />
        <img class="option-active" src="${require('@/assets/icons/editor/chevron-down@2x(1).png')}" />
    </div>
    <div class="subfield-item line-style" title="线型">
        <img src="${require('@/assets/icons/editor/line-shape.png')}"  />
        <img class="option-active" src="${require('@/assets/icons/editor/chevron-down@2x(1).png')}" />
    </div>
    <div class="subfield-item line-weight" title="粗细">
        <img src="${require('@/assets/icons/editor/line-height.png')}"  />
        <img class="option-active" src="${require('@/assets/icons/editor/chevron-down@2x(1).png')}" />
    </div>
    </div>
    `
    // <div class="subfield-item tox-tbtn" title="对齐" data-select="left">
    //     <img src="${require('@/assets/icons/editor/text-left.png')}"  />
    //     <img class="option-active" src="${require('@/assets/icons/editor/chevron-down@2x(1).png')}" />
    // </div>
// 创建分割线列表块结构
const divideDom = document.createElement('div')
divideDom.classList.add('divide-list')
/*<div class="divide-box line-bg" >
  <div class="line-dot-line"></div>
</div>*/
divideDom.innerHTML = `
    <div class="divide-box line-bg">
        <div class="line-base"></div>
      </div>


      <div class="divide-box line-bg" >
        <div class="line-gradation"></div>
      </div>

      <div class="divide-box line-bg" >
        <div class="line-double-undertint"></div>
      </div>
      <div class="divide-box line-bg" >
        <div class="line-double-dotted"></div>
      </div>

      <div class="divide-box line-bg" >
        <div class="line-lang-dotted"></div>
      </div>

      <div class="divide-box line-bg" >
        <div class="line-gradation-dotted"></div>
      </div>
      <div class="divide-box line-bg" >
        <div class="line-oblique"></div>
      </div>
      <div class="divide-box line-bg" >
        <div class="line-dot"></div>
      </div>
`
divideDom.style.display = 'none'
// 创建线宽列表结构
const lineWeightDom = document.createElement('div')
lineWeightDom.classList.add('line-weight-list')
lineWeightDom.innerHTML= `
    <div class="line-item" data-weight="line-1">
        <span>1pt</span>
        <div class="line-1"></div>
    </div>
    <div class="line-item" data-weight="line-2">
        <span>2pt</span>
        <div class="line-2"></div>
    </div>
    <div class="line-item" data-weight="line-3">
        <span>3pt</span>
        <div class="line-3"></div>
    </div>
    <div class="line-item" data-weight="line-4">
        <span>4pt</span>
        <div class="line-4"></div>
    </div>
    <div class="line-item" data-weight="line-5">
        <span>5pt</span>
        <div class="line-5"></div>
    </div>
`
lineWeightDom.style.display = 'none'
// const textAlignDom = document.createElement('div')
// textAlignDom.classList.add('tox-collection-list')
// textAlignDom.innerHTML = `
//     <div style="display:flex">
//         <div class="tox-collection__item" data-value="left">
//             <img src="${require('@/assets/icons/editor/text-left.png')}" />
//         </div>
//         <div class="tox-collection__item" data-value="center">
//             <img src="${require('@/assets/icons/editor/text-center.png')}" />
//         </div>
//         <div class="tox-collection__item" data-value="right">
//             <img src="${require('@/assets/icons/editor/text-right.png')}" />
//         </div>
//         <div class="tox-collection__item" data-value="justify">
//             <img src="${require('@/assets/icons/editor/text-justify.png')}" />
//         </div>
//     </div>
//     `
// textAlignDom.style.display = 'none'


// 创建纵向拖拽条结构
const lengthwaysDom = document.createElement('div')
lengthwaysDom.classList.add('lengthways-box')
lengthwaysDom.style.visibility = 'hidden'
lengthwaysDom.innerHTML = `
    <div class="lengthways-add">+</div>
    <div class="twig"></div>
    <div class="del-chunk"><img src="${require('@/assets/icons/editor/del-subfield.png')}" /></div>
`
subfieldBoxDom.appendChild(lengthwaysDom)
// 创建横向拖拽条结构
const crosswiseDom = document.createElement('div')
crosswiseDom.classList.add('crosswise-box')
crosswiseDom.style.visibility = 'hidden'
crosswiseDom.innerHTML = `
    <div class="crosswise-add">+</div>
    <div class="twig"></div>
    <div class="del-chunk"><img src="${require('@/assets/icons/editor/del-subfield.png')}" /></div>
`
subfieldBoxDom.appendChild(crosswiseDom)


let activeEditor = null
let subfieldDom = null
let left = null
let bottom = null
let uuid = null
let visible = 'hidden'
let domList = []
let isActiveUid = []
let activeDom = null    // 当前选中的dom
let lineActive = null // 当前激活的分割线角标dom
let iframeDom = null

// 拖拽条参数 纵向&横向
let directionLeft = null
let directionBottom = null
// 分栏子模块
let leftDom = subfieldBoxDom.querySelector('.subfield-item.set-left')
let rightDom = subfieldBoxDom.querySelector('.subfield-item.set-right')
let paletteDom = subfieldBoxDom.querySelector('.palette')
let lineStyleDom = subfieldBoxDom.querySelector('.line-style')
let weightDom = subfieldBoxDom.querySelector('.line-weight')
// let toxTbtnDom = subfieldBoxDom.querySelector('.tox-tbtn')
// 拖拽条子模块
let crosswiseAddDom = crosswiseDom.querySelector('.crosswise-add')
let lengthwaysAddDom = lengthwaysDom.querySelector('.lengthways-add')
let crosswiseDelDom = crosswiseDom.querySelector('.del-chunk')
let lengthwaysDelDom = lengthwaysDom.querySelector('.del-chunk')


// 初始化 将子模块添加至父级
if(!document.querySelector('#subfield-box')){
    document.body.appendChild(subfieldBoxDom)
    paletteDom.appendChild(colorPalette)
    lineStyleDom.appendChild(divideDom)
    weightDom.appendChild(lineWeightDom)
    // toxTbtnDom.appendChild(textAlignDom)
}

/**
 * 初始化分栏功能
 *
 * @param editor 编辑器实例
 */
function subfieldinit(editor){
    activeEditor = editor
    subfieldDom = document.querySelector('.subfield')
    setTimeout(() => {
        // 页面加载后，初始化元素绑定事件
        bindTapEvent()
        // 编辑器变更后，重新绑定事件
        activeEditor.on('SetContent', bindTapEvent)
        // 滚动事件
        scrollHandler()
        // 分栏菜单点击事件
        subfieldDom.addEventListener('click', subfieldClickevent)
        // 初始化获取iframe
        iframeDom = document.querySelectorAll(`#${editor.id}_ifr`)[0]
    },0)
}
// 编辑器变更后，重新绑定事件
function bindTapEvent(){
    domList = activeEditor.dom.select('.subfield-tap')
    // 更新dom结构列表，重新绑定事件
    updateDom()
}
// 数据变更后，更新编辑器分栏结构，并重新绑定事件
function updateDom(){
    domList = activeEditor.dom.select('.subfield-tap')
    domList.forEach(dom => {
        // 避免事件多次被执行，当编辑器内容变更后将之前的事件解绑，重新绑定
        activeEditor.dom.unbind(dom, 'click', eventHandler)
        activeEditor.dom.bind(dom, 'click', eventHandler)
    });
    closeColorPalette()
    closeLineStyle()
    closeLineWeight()
    closedirection()
    closeSubfield()
}
// 元素绑定事件
function eventHandler(o){
    let dom = o.currentTarget
    let clientWidthLet = ((dom.clientWidth + 3) / 2) - 15;
    let activeDomRect = dom.getBoundingClientRect()
    let iframeRect = iframeDom.getBoundingClientRect()
    let oldActiveDom = null
    console.log(dom)
    if (dom.classList.contains('divide-box')) {
        // 选中分割线，隐藏分栏相关模块
        paletteDom.style.display = 'none'
        leftDom.style.display = 'none'
        rightDom.style.display = 'none'
        // toxTbtnDom.style.display = 'none'
        lineStyleDom.style.display = 'block'
        weightDom.style.display = 'block'
    } else {
        // 选中分栏，隐藏分割线相关模块
        paletteDom.style.display = 'block'
        leftDom.style.display = 'block'
        rightDom.style.display = 'block'
        // toxTbtnDom.style.display = 'block'
        lineStyleDom.style.display = 'none'
        weightDom.style.display = 'none'
    }
    // 判断当前模块是否聚焦状态，并且点击位置是否在激活分栏小图标上
    if (dom.classList.contains('active-subfield') &&
        o.offsetY > -8 &&
        o.offsetY < 8 &&
        o.offsetX > clientWidthLet &&
        o.offsetX < clientWidthLet + 30) {
        // 头部小图标,点击激活或关闭分栏菜单
        if (visible === 'hidden') {
            visible = 'visible'
            dom.classList.add('hover-btn')
        } else {
            visible = 'hidden'
            dom.classList.remove('hover-btn')
        }
        left = iframeRect.left + activeDomRect.left + activeDomRect.width / 2 - subfieldDom.clientWidth / 2
        console.log(o, subfieldDom.clientWidth)
        bottom = window.innerHeight - activeDomRect.top - 110
        subfieldDom.style = `left:${left}px;bottom:${bottom}px;visibility:${visible}`
        if (!activeDom){
            activeDom = dom
        }
        // 初始化调色盘
        initPallette(dom, activeEditor,{},45)
        return
    }
    // 循环遍历所有分栏，判断是否是激活状态
    domList.forEach(dom => {
        if (dom.getAttribute('subfield-uuid')) {
            isActiveUid.push(dom.getAttribute('subfield-uuid'))
            oldActiveDom = dom
        }
    })
    // 判断是否已存在聚焦模块，如果存在，则取消，并设置新模块聚焦操作
    if (isActiveUid?.length && !dom.getAttribute('subfield-uuid') || isActiveUid?.length && !isActiveUid.includes(dom.getAttribute('subfield-uuid'))) {
        console.log('有子分栏，不允许添加', isActiveUid, dom.getAttribute('subfield-uuid'))
        oldActiveDom.classList.remove('active-subfield')
        dom.classList.remove('hover-btn')
        activeEditor.dom.setAttribs(oldActiveDom, { 'subfield-uuid': '' })
        isActiveUid = []
        subfieldDom.style = `visibility:hidden`
        visible = 'hidden'
        closedirection()
        closeColorPalette()
        closeLineStyle()
        closeLineWeight()
        // closeTextAlign()
        setTimeout(()=>{
            eventHandler(o)
        },0)
        return
    } else {
        // 判断是否已存在聚焦模块，如果存在，则取消聚焦状态
        if (dom.classList.contains('active-subfield')) {
            console.log('删除')
            dom.classList.remove('active-subfield')
            activeEditor.dom.setAttribs(dom, { 'subfield-uuid': '' })
            uuid = null
            left = null
            bottom = null
            isActiveUid = []
            subfieldDom.style = `visibility:hidden`
            visible = 'hidden'
            dom.classList.remove('hover-btn')
            activeDom = null
            closedirection()
            closeColorPalette()
            closeLineStyle()
            closeLineWeight()
            // closeTextAlign()
        } else {
            // 添加聚焦状态
            console.log('添加', o)
            uuid = generateUUID()
            activeEditor.dom.setAttribs(dom, { 'subfield-uuid': uuid })
            dom.classList.add('active-subfield')
            activeDom = dom
            let domMargin = dom.nextElementSibling ? getComputedStyle(dom.nextElementSibling) :getComputedStyle(dom)
            let marginLeft = parseInt(domMargin.getPropertyValue('margin-left'))/2
            let marginTop = parseInt(domMargin.getPropertyValue('margin-top'))/2
            // 拖拽条位置
            let visible = 'visible'
            if (dom.getAttribute('data-direction') === 'lengthways'){
                // 纵向
                let height = dom.clientHeight
                let distanceToBottom = getDistanceToBottom(dom)
                console.log(distanceToBottom,8888)
                directionLeft = iframeRect.left + activeDomRect.left + activeDomRect.width - 15 + marginLeft
                directionBottom = window.innerHeight - activeDomRect.top - activeDomRect.height - 122
                if (distanceToBottom < 0){
                    height += (distanceToBottom - 15)
                    directionBottom -= (distanceToBottom - 15)
                }
                lengthwaysDom.style = `left:${directionLeft}px;bottom:${directionBottom}px;height:${height}px;visibility:${visible}`
            } else if (dom.getAttribute('data-direction') === 'crosswise'){
                // 横向
                let width = dom.clientWidth
                directionLeft = iframeRect.left + activeDomRect.left
                directionBottom = window.innerHeight - activeDomRect.top - activeDomRect.height - 138 - marginTop
                crosswiseDom.style = `left:${directionLeft}px;bottom:${directionBottom}px;width:${width}px;visibility:${visible}`
            }
            console.log(o, iframeRect, activeDomRect,'拖拽条位置')
        }
    }
}
// 编辑器滚动事件
function scrollHandler(){
    let iframeDom = document.querySelectorAll(`#${activeEditor.id}_ifr`)[0]
    console.log('iframeDom', iframeDom)
    iframeDom.contentWindow.document.addEventListener('scroll', () => {
        subfieldDom.style = `visibility:hidden`
        visible = 'hidden'
        activeDom && activeDom.classList.remove('hover-btn')
        closedirection()
        closeColorPalette()
        closeLineStyle()
        closeLineWeight()
        // closeTextAlign()
    })
}

// 分割线列表点击事件
divideDom.addEventListener('click', (e) => {
    if (e.target && e.target.classList.contains('divide-list')) return
    let className = ''
    if (e.target && e.target.classList.contains('divide-box')) {
        className = e.target.children[0].classList[0]
    } else if (e.target && (e.target.classList.contains('dot')||e.target.parentNode.classList.contains('dot'))){
        className = 'line-dot-line'
    }else{
        className = e.target.classList[0]
    }
    if (className != 'line-dot-line'){
        activeEditor.dom.setHTML(activeDom, `<div class="${className}" contenteditable="false"></div>`)
    }else{
        activeEditor.dom.setHTML(activeDom, `<div class="line-dot-line"></div><div class="dot" contenteditable="false"><span contenteditable="false"></span></div>`)
        activeDom.classList.add('default-bg')
    }
    const list = divideDom.children
    Array.from(list).forEach(el=>{
        el.classList.remove('active-line')
        if(el.children[0].classList[0] === className){
            el.classList.add('active-line')
        }
    })
    e.stopPropagation()
})

// 线宽列表点击事件
lineWeightDom.addEventListener('click', (e) => {
    if (e.target && e.target.classList.contains('line-weight-list')) return
    let className = ''
    if (e.target && e.target.classList.contains('line-item')) {
        className = e.target.getAttribute('data-weight')
    }else{
        className = e.target.parentNode.getAttribute('data-weight')
    }
    console.log(activeDom)
    if (activeDom.children[0].classList[1]){
        activeDom.children[0].classList.remove(activeDom.children[0].classList[1])
        activeDom.children[0].classList.add(className)
    }else{
        activeDom.children[0].classList.add(className)
    }
    const list = lineWeightDom.children
    Array.from(list).forEach(el => {
        el.classList.remove('active-line')
        if (el.getAttribute('data-weight') === className) {
            el.classList.add('active-line')
        }
    })
    e.stopPropagation()
 })
// 对齐列表点击事件
// textAlignDom.addEventListener('click', (e) => {
//     console.log(e,111)
//     if (e.target && e.target.parentNode.classList.contains('tox-collection__item')) {
//         let className = e.target.parentNode.getAttribute('data-value')
//         let url = e.target.currentSrc
//         toxTbtnDom.children[0].src = url
//         activeEditor.dom.setStyle(activeDom, `text-align`, className)
//         Array.from(textAlignDom.children[0].children).forEach(el => {
//             el.classList.remove('align-active')
//             if (el.getAttribute('data-value') === className) {
//                 el.classList.add('align-active')
//             }
//         })
//     }
//     e.stopPropagation()
//  })

// 清除聚焦状态
function clear(){
    uuid = null
    left = null
    bottom = null
    isActiveUid = []
    subfieldDom.style = `visibility:hidden`
    visible = 'hidden'
    activeDom = null
    updateDom()
}
// 分栏菜单点击事件
function subfieldClickevent(e){
    if (e.target && e.target.parentNode) {
        let nodeClass = ''
        let parentNode = null
        if (e.target.classList.contains('subfield-item')){
            nodeClass = e.target.classList[1]
            parentNode = e.target
        }else{ 
            nodeClass = e.target.parentNode.classList[1]
            parentNode = e.target.parentNode
        }
        if (nodeClass === 'del'){
            // 删除
            console.log('删除')
            activeEditor.dom.remove(activeDom)
            clear()
        } else if (nodeClass === 'set-left'){
            // 左边新增一栏
            console.log('左边新增一栏')
            let getDom = activeEditor.dom.getOuterHTML(activeDom)
            const regex = /(?:\s+active-subfield\b)|(?:\s+hover-btn\b)|\b(subfield-uuid\s*=\s*(?:"[^"]*"|'[^']*'))/g;
            getDom = getDom.replace(regex, '')
            let newDom = activeEditor.dom.createFragment(getDom)
            if (activeDom.parentNode) {
                activeDom.parentNode.insertBefore(newDom, activeDom)
                updateDom()
            }
        }else if (nodeClass === 'set-right'){
            // 右边新增一栏
            addSameDom(e)
        } else if (nodeClass === 'palette'){
            // 调色板
            console.log('调色板')
            let optionActive = parentNode.querySelector('.option-active')
            colorPaletteClick(e, optionActive,(isHow)=>{
                if(isHow){
                    optionActive.style.transform = 'rotate(180deg)'
                }else{
                    optionActive.style.transform = 'rotate(0deg)'
                }
            })
            closeLineStyle()
            closeLineWeight()
            // closeTextAlign()
        } else if (nodeClass === 'line-style'){
            // 线形
            console.log('线形')
            closeColorPalette()
            closeLineWeight()
            let optionActive = parentNode.querySelector('.option-active')
            lineStyleShow(divideDom,optionActive)
            let className = activeDom.children[0].classList[0]
            const list = divideDom.children
            Array.from(list).forEach(el => {
                el.classList.remove('active-line')
                if (el.children[0].classList[0] === className) {
                    el.classList.add('active-line')
                }
            })
        }else if (nodeClass === 'line-weight'){
            // 线宽
            console.log('线宽')
            closeColorPalette()
            closeLineStyle()
            let optionActive = parentNode.querySelector('.option-active')
            lineStyleShow(lineWeightDom, optionActive)
            let className = activeDom.children[0].classList[1]
            console.log(className)
            const list = lineWeightDom.children
            Array.from(list).forEach(el => {
                el.classList.remove('active-line')
                if (el.getAttribute('data-weight') === className) {
                    el.classList.add('active-line')
                }
            })
        } else if (nodeClass === 'tox-tbtn'){
            // console.log('设置')
            // closeColorPalette()
            // closeLineStyle()
            // closeLineWeight()
            // let optionActive = parentNode.querySelector('.option-active')
            // lineStyleShow(textAlignDom, optionActive)
            // let alignActive = parentNode.getAttribute('data-select') || 'left'
            // let alignDomList =  Array.from(textAlignDom.children[0].children)
            // alignDomList.forEach(el => {
            //     if (el.getAttribute('data-value') == alignActive){
            //         el.classList.add('align-active')
            //     } else {
            //         el.classList.remove('align-active')
            //     }
            // })
            // console.log(textAlignDom.children[0].children,99999)

        }
    }
    console.log('subfieldClickevent', e)
}
// 线形/线宽 列表展示
function lineStyleShow(dialogDom,dom){
    if(dom) lineActive = dom
    if (dialogDom.style.display === 'none') {
        dialogDom.style.display = 'block'
        if (lineActive) lineActive.style.transform = 'rotate(180deg)'
    } else {
        dialogDom.style.display = 'none'
        if(lineActive) lineActive.style.transform = 'rotate(0deg)'
    }
}
// 对齐方式列表关闭
// function closeTextAlign() {
//     textAlignDom.style.display = 'none'
//     if (lineActive) lineActive.style.transform = 'rotate(0deg)'
// }
// 线形列表关闭
function closeLineStyle(){
    divideDom.style.display = 'none'
    if (lineActive) lineActive.style.transform = 'rotate(0deg)'
}
// 线宽列表关闭
function closeLineWeight() {
    lineWeightDom.style.display = 'none'
    if (lineActive) lineActive.style.transform = 'rotate(0deg)'
}
// 拖拽条头部点击事件
crosswiseAddDom.addEventListener('click', addSameDom)
lengthwaysAddDom.addEventListener('click', addSameDom)
lengthwaysDelDom.addEventListener('click', delSameDom)
crosswiseDelDom.addEventListener('click', delSameDom)

// ------- 拖拽条鼠标按下事件 & 参数------------------
let startPosition = null
let isDraggingY = false
let directionDefaultBottom = null
let oldHeight = null
let resultY = null
let oldResultY = null

let isDraggingX = false
let directionDefaultLeft = null
let oldWidth = null
let resultX = null
let oldResultX = null
let isFlex = true // 拖拽条其余元素是否存在flex布局
let differenceWidth = 0 // 父子节点宽度差值
let marginLeft = null
// 纵向拖拽条鼠标按下事件，允许执行move事件
crosswiseDom.addEventListener('mousedown', (e) => {
    if (e.target.classList.contains('crosswise-add')) return
    // 记录鼠标按下位置
    startPosition = e.pageY
    isDraggingY = true
    directionDefaultBottom = directionBottom
    oldHeight = activeDom.offsetHeight
})
// 纵向拖拽条抬起事件，设置焦点模块宽度，重置初始化数据
crosswiseDom.addEventListener('mouseup', (e) => {
    if (e.target.classList.contains('crosswise-add')) return
    console.log('oldHeight', oldHeight, resultY + oldHeight)
    isDraggingY = false
    crosswiseMouseup()
    
})
// 横向拖拽条鼠标按下事件，允许执行move事件，添加动画过渡
lengthwaysDom.addEventListener('mousedown', (e) => {
    if (e.target.classList.contains('lengthways-add')) return
    let domMargin = activeDom.nextElementSibling ? getComputedStyle(activeDom.nextElementSibling) : getComputedStyle(activeDom)
    marginLeft = parseInt(domMargin.getPropertyValue('margin-left')) / 2
    // 记录鼠标按下位置
    startPosition = e.pageX
    isDraggingX = true
    directionDefaultLeft = directionLeft
    oldWidth = activeDom.offsetWidth
    lengthwaysDom.style.transition = 'none'
    let parentNode = activeDom.parentNode
    let parentNodeWidth = parentNode.clientWidth - parentNode.style.paddingLeft - parentNode.style.paddingRight
    let childrenWidth = 0
    let tempFlex = false
    Array.from(parentNode.children).forEach((el) => {
        let flex = window.getComputedStyle(el).getPropertyValue('flex')
        if (String(flex||'') == '1 1 0%'){
            tempFlex = true
            let computedStyle = getComputedStyle(el)
            if (activeDom == el){
                childrenWidth += el.offsetWidth + parseInt(parseInt(computedStyle.getPropertyValue('margin-left')))
            }else{
                childrenWidth += 80 + parseInt(computedStyle.getPropertyValue('margin-left'))
            }
        }else{
            let offsetWidth = el.offsetWidth + parseInt(getComputedStyle(el).getPropertyValue('margin-left'))
            childrenWidth += offsetWidth
        }
    })
    isFlex = tempFlex
    differenceWidth = parentNodeWidth - childrenWidth
    console.log('lastNode', parentNodeWidth, childrenWidth, differenceWidth,'兄弟元素是否存在flex:1',isFlex)
})
// 横向拖拽条抬起事件，设置焦点模块宽度，重置初始化数据
lengthwaysDom.addEventListener('mouseup', (e) => {
    if(e.target.classList.contains('lengthways-add')) return
    console.log('oldWidth',e, oldWidth, resultX + oldWidth)
    isDraggingX = false
    lengthwaysMouseup()

})
// 通用鼠标移动事件
document.addEventListener('mousemove', (e) => {
    // 横向拖拽条，计算移动距离
    if (isDraggingY) {
        resultY = (e.pageY - startPosition)
        // 判断是否达到焦点模块预设临界值，达到后自动执行鼠标抬起事件拖拽条不再计算（统一设置为80
        if (oldHeight < 80 && resultY < 0 || oldHeight + resultY < 80 && resultY < 0) {
            crosswiseMouseup()
            return
        }
        let moveDistance = directionDefaultBottom - resultY
        crosswiseDom.style.bottom = moveDistance + 'px'
        directionBottom = moveDistance
        oldResultY = resultY
        console.log('移动高度Y', resultY)
    }
    // 纵向拖拽条，计算移动距离
    if (isDraggingX) {
        resultX = (e.pageX - startPosition)
        // 节点的拖拽方向，防止拖拽条越界
        if (resultX > 0 && differenceWidth - resultX <= 0){
            lengthwaysMouseup()
            return
        }
        // 判断是否达到焦点模块预设临界值，达到后自动执行鼠标抬起事件拖拽条不再计算（统一设置为80
        if ( resultX < 0 && oldWidth <= 80 || oldWidth + resultX <= 80 && resultX < 0) {
            lengthwaysMouseup()
            return
        }
        let moveDistance = directionDefaultLeft + resultX
        lengthwaysDom.style.left = moveDistance + 'px'
        directionLeft = moveDistance
        oldResultX = resultX
        console.log('移动高度X', resultX)
    }
})
// 横向鼠标抬起的清空执行事件（复用
function crosswiseMouseup() {
    isDraggingY = false
    activeEditor.dom.setStyles(activeDom, { 'height': oldResultY +oldHeight + 'px','box-sizing': 'border-box'})
    startPosition = null
    directionDefaultBottom = null
    resultY = null
    oldResultY = null
}
// 纵向鼠标抬起的清空执行事件（复用
function lengthwaysMouseup() {
    isDraggingX = false
    let tempWidth = oldResultX + oldWidth
    activeEditor.dom.setStyles(activeDom, { 'width': tempWidth + 'px','flex':'0 0 auto', 'box-sizing': 'border-box' })
    activeDom.offsetWidth; // 这个属性的访问可以触发重绘
    lengthwaysDom.style.transition = 'all 0.2s linear'
    setTimeout(()=>{
        requestAnimationFrame(() => {
            let activeDomRect = activeDom.getBoundingClientRect();
            let iframeRect = iframeDom.getBoundingClientRect();
            let height = activeDomRect.height
            let distanceToBottom = getDistanceToBottom(activeDom)
            directionLeft = iframeRect.left + activeDomRect.left + activeDomRect.width - 15 + marginLeft
            directionBottom = window.innerHeight - activeDomRect.top - activeDomRect.height - 120
            if (distanceToBottom < 0) {
                height += (distanceToBottom - 15)
                directionBottom -= (distanceToBottom - 15)
            }
            lengthwaysDom.style.left = directionLeft + 'px';
            lengthwaysDom.style.height = height + 'px';
            lengthwaysDom.style.bottom = directionBottom + 'px';
            console.log(directionLeft, marginLeft,'纵向')
            marginLeft = null
        });
    },500)
    startPosition = null
    directionDefaultLeft = null
    resultX = null
    oldResultX = null
    differenceWidth = 0
}
// ----------------- 拖拽条相关功能结束 -------------------

// 根据选中块，新增一条相同模块
function addSameDom(e) {
    e.stopPropagation()
    e.preventDefault()
    let getDom = activeEditor.dom.getOuterHTML(activeDom)
    const regex = /(?:\s+active-subfield\b)|(?:\s+hover-btn\b)|\b(subfield-uuid\s*=\s*(?:"[^"]*"|'[^']*'))/g;
    getDom = getDom.replace(regex, '')
    let newDom = activeEditor.dom.createFragment(getDom)
    if (activeDom.parentNode) {
        activeEditor.dom.insertAfter(newDom, activeDom)
        updateDom()
    }
}
// 根据选中块删除模块
function delSameDom(e){
    e.stopPropagation()
    e.preventDefault()
    activeEditor.dom.remove(activeDom)
    clear()
}
// 关闭所有拖拽条显示
function closedirection(){
    lengthwaysDom.style = `left:0;bottom:0;height:0;visibility:hidden`
    crosswiseDom.style = `left:0;bottom:0;height:0;visibility:hidden`
}
// 关闭分栏菜单显示
function closeSubfield(){
    left = 0;
    bottom = 0;
    visible = 'hidden'
    activeDom && activeDom.classList.remove('hover-btn')
    subfieldDom.style = `left:0;bottom:0;visibility:hidden`
}
// 生成UUID
function generateUUID() {
    // 这里只是一个简单的示例，你可以使用更复杂的UUID生成库  
    return (Math.random() * 16).toString(16);
}
// 获取dom 距离窗口底部的距离
function getDistanceToBottom(element) {
    // 获取元素的位置信息
    var rect = element.getBoundingClientRect();

    // 获取窗口的可视高度
    var windowHeight = window.innerHeight || document.documentElement.clientHeight;
    // 计算元素距离窗口底部的距离
    var distanceToBottom = windowHeight - (rect.top + rect.height) - 64;

    return distanceToBottom;
}

export {
    subfieldinit,
    clear
}